﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using RearLivestock.Common.Domains.zjy;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.RBAC.Api.Application.zjyApplication.Commands.Permissionses
{
    public class SearchPermissionsHandler : IRequestHandler<SearchPermissionsCommand, Result<List<Permissions>>>
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchPermissionsHandler> _logger;

        /// <summary>
        /// 权限仓储
        /// </summary>
        private readonly IBaseRepository<Permissions> permissionsRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="permissionsRepository"></param>
        public SearchPermissionsHandler(ILogger<SearchPermissionsHandler> logger,
            IBaseRepository<Permissions> permissionsRepository)
        {
            _logger = logger;
            this.permissionsRepository = permissionsRepository;
        }

        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result<List<Permissions>>> Handle(SearchPermissionsCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<List<Permissions>>() { Code = (int)CommonErrorCode.Search };
            try
            {
                var query = await (await permissionsRepository.GetAll()).ToListAsync();
                if (query != null)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = query;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("获取权限功能异常" + ex.Message);
            }
            return result;
        }
    }
}
